package com.hyyt.shopjsp.basic.controller;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicUsersService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Zhang Dingfang on 2016/10/24 0024下午 7:07.
 */
@Controller
@RequestMapping("/back/users")
public class BasicUsersController extends BaseController {
    private Logger log = Logger.getLogger(BasicUsersController.class);
    private String basePath = "/back/basic/users/";

    @Resource
    private IBasicUsersService basicUsersService;

    /**
     * 进入管理员管理
     *
     * @return 进入指定页面
     */
    @RequestMapping("gotoUsersPage")
    public String gotoUsersPage() {
        return basePath + "usersList";
    }


    /**
     * 查询所有后台管理员
     *
     * @param page
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "listUsers", method = RequestMethod.POST)
    @ResponseBody
    public void listUsers(String lockState, String userName, Page page, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        if (Utils.objectIsNotEmpty(lockState)) {
            param.put("lockState", lockState);
        }
        if (Utils.objectIsNotEmpty(userName)) {
            param.put("userName", userName);
        }
        param.put("sortColumns", "usersId desc");
        int totalRecordCount = basicUsersService.countBasicUsers(param);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        //定义查询的字段
        String [] selectColmunsArray={"usersId","userPhoto","userName","trueName","phone","email","lockState","registerDate"};
        param.put("selectColmunsArray",selectColmunsArray);
        List<BasicUsers> list = basicUsersService.queryBasicUsers(param, page.getPageRecordBeginIndex(), page.getPageSize());
        param.clear();
        param.put("total", totalRecordCount);// total键 存放总记录数，必须的
        param.put("rows", list);// rows键 存放每页记录 list
        ResultMsg.create(param, response);  //把内容发送到页面
    }

    /**
     * 根据用户id获得用户对象
     *
     * @param usersId
     */
    @RequestMapping(value = "getUsersObject", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getUsersObject(Integer usersId) {
        if (Utils.objectIsNotEmpty(usersId)) {
            BasicUsers users = basicUsersService.loadBasicUsers(usersId);
            return ResultMsg.create(true, null, FastJsonUtils.toJSONString(users));
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 根据传入的用户id集合（以,隔开的字符串）
     *
     * @param usersId
     */
    @RequestMapping(value = "deleteUsers", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteUsers(Integer usersId) {
        if (Utils.objectIsNotEmpty(usersId)) {
            basicUsersService.deleteBasicUsers(usersId);
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 检查用户名是否已经存在
     *
     * @param userName 用户名
     * @param usersId  用户id
     * @return
     */
    @RequestMapping(value = "checkUsers", method = RequestMethod.POST)
    @ResponseBody
    public Map checkUsers(String userName, Integer usersId) {
        Map<String, Object> param = new HashMap<>();
        boolean flag=false;
        if (Utils.objectIsNotEmpty(userName)) {
            //统计名字的个数
            param.put("userName", userName);
            int countUserName = basicUsersService.countBasicUsers(param);

            if (countUserName > 0) {
                if (Utils.objectIsNotEmpty(usersId)) {
                    //统计名字是否为当前用户的
                    param.put("usersId", usersId);
                    int countUsersId = basicUsersService.countBasicUsers(param);
                    if (countUsersId == 1) {
                        flag=true;
                    }
                }
            } else {
                flag=true;
            }
        }
        param.clear();
        param.put("valid",flag);//bootstrap validator 远程校验需要返回{"valid",true}
        return param;
    }

    /**
     * 保存或者修改用户信息
     *
     * @param basicUsers
     * @return
     */
    @RequestMapping(value = "saveOrUpdateUsers", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveOrUpdateUsers(BasicUsers basicUsers) {
        if (Utils.objectIsNotEmpty(basicUsers)) {
            if (Utils.objectIsEmpty(basicUsers.getUsersId())) {
                basicUsers.setRegisterDate(new Timestamp(System.currentTimeMillis()));
                basicUsersService.saveBasicUsers(basicUsers);
            } else {
                basicUsersService.updateBasicUsers(basicUsers);
            }
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 校验当前用户输入的旧密码是否正确
     *
     * @throws IOException
     */
    @RequestMapping(value = "checkOldPassWord")
    @ResponseBody
    public ResultMsg checkOldPassWord(String parameter) throws IOException {
        boolean isSuccess = false;//默认不正确
        BasicUsers users = getSessionUsers();
        if (parameter != null && !"".equals(parameter)) {
            String dataPassword = users.getPassword();
//			String encodeMd5 = Utils.EncodeMd5(Utils.EncodeMd5(parameter));
            if (dataPassword.equals(parameter)) {
                isSuccess = true;
            }
        }
        return ResultMsg.create(isSuccess);
    }

    /**
     * 跳转至修改密码页面
     * @return
     */
    @RequestMapping("goToupdatePasswordPage")
    public String goToupdatePasswordPage(){
        return basePath + "changePassword";
    }

    /**
     * 修改密码
     * @param password
     * @return
     */
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg updatePassword(String password){
        BasicUsers users = getSessionUsers();
        Map<String ,Object>params = new HashMap<>();
        if (Utils.objectIsNotEmpty(password)&&Utils.objectIsNotEmpty(users.getUsersId())){
            params.put("password",password);
            params.put("usersId",users.getUsersId());
            basicUsersService.updatePwd(params);
            return ResultMsg.create(true);
        }else{
            return ResultMsg.create(false);
        }
    }
}